<template>
  <el-row class="my-company-container">
    <el-col :span="24"
            id="headerTitle">
      <div class="header-box">
        <p class="unit-list">
          <el-tooltip class="item"
                      effect="dark"
                      content="返回"
                      placement="top">
            <span class="el-icon-back"
                  id="backIconStyle"
                  @click="goBack"></span>
          </el-tooltip>
          &nbsp;&nbsp;单位列表
        </p>
        <p>
          <span>默认单位</span>
          <!-- @change="onChangeComp" -->
          <el-select v-model="company_id"
                     class="select-style"
                     :disabled="true"
                     placeholder="请选择">
            <el-option v-for="(item,index) in compArr"
                       :key="index"
                       :label="item.org_name"
                       :value="item.company_id">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="onJoinCom">加入组织</el-button>
          <el-button type="primary"
                     @click="onAddOrLookCom('创建单位','')">创建组织</el-button>
        </p>
      </div>
    </el-col>
    <el-col :span="24"
            class="container">
      <ul>
        <li v-for="(item, index) in companyArr"
            @mouseenter="showDialog(index)"
            @mouseleave="hideDialog(index)"
            :accesskey="index"
            :key="index">
          <div class="li-content">
            <div class="li-content-left">
              <img :src="item.company_logo"
                   alt="">
            </div>
            <div class="li-content-right">
              <p class="com-name">{{item.company_name}}</p>
              <div class="right-main-content">
                <p>{{item.province}}{{item.city}}{{item.area}}{{item.addr}}</p>
              </div>
            </div>
          </div>
          <!--操作蒙层-->
          <div class="handleDialog"
               v-show="ishow && index==current">
            <el-col :sapn="24"
                    class="opera-button">
              <el-button :type="item.status==3?'primary':'info'"
                         :disabled="item.status==3?false:true"
                         @click="onAddOrLookCom('查看单位',item)">查看单位</el-button>
              <el-button :type="item.status==3?'primary':'info'"
                         :disabled="item.status==3?false:true"
                         @click="entryPlatf(item)">进入平台</el-button>
              <!--普通用户按钮‘业务系统申请’不显示;管理员用户按钮‘业务系统申请’显示;-->
              <!-- <el-button :type="item.status==3?'primary':'info'"
                         :disabled="item.status==3?false:true"
                         v-show="item.create_id==user_id"
                         @click="onBusinessApp(item)">业务系统申请</el-button> -->
              <!-- v-auth="$route.query.topPage == '平台里跳转'?'mid-business-system-app-button':'mid-business-system-app-butt'" -->
            </el-col>
          </div>
        </li>
      </ul>
    </el-col>
    <el-col :span="24"
            class="bottom-box">
      <el-pagination align="center"
                     :current-page="requestParams.page"
                     :page-sizes="[12]"
                     :page-size="requestParams.page_size"
                     :total="total"
                     layout="total, sizes, prev, pager, next, jumper"
                     @current-change="handleCurrentChange"></el-pagination>
    </el-col>
    <el-dialog title="加入组织"
               :visible.sync="joinComDialogVisible"
               width="40%"
               :before-close="handleClose">
      <JoinCompany :childValueToParent="childValueToParent"
                   :isReset="isReset">
      </JoinCompany>
    </el-dialog>
    <el-dialog title="进入平台"
               class="entry-plat"
               :visible.sync="entryPlatDialogVisible"
               width="55%"
               :before-close="entryPlatHandleClose">
      <SelPlatDialog :judgeOpen="judgeOpen"
                     :entryPlatObj="entryPlatObj">
      </SelPlatDialog>
    </el-dialog>
    <GuidePage :isOpen.sync="guideDialog"
               @isOne="closeOne"></GuidePage>
  </el-row>
</template>

<script>
import GuidePage from './Components/GuidePage';
import JoinCompany from './Components/JoinCompany';
import SelPlatDialog from './Components/SelPlatDialog';
import { MyCompanyApi } from '@/services/WorkBench';
import { userPermissionApi } from "@/services/UserPermission";
export default {
  components: {
    JoinCompany,
    SelPlatDialog,
    GuidePage
  },
  data () {
    return {
      onlyOne: true,
      guideDialog: false, //引导页弹窗
      userMenu: [],//用户菜单 
      user_id: '',//用户主键值
      user_type: '',//用户类型->管理员：3；普通用户：4；
      company_id: '',
      requestParams: {
        page: 1,
        page_size: 12,
        is_page: 1,
      },
      total: 0,
      entryPlatObj: {},
      judgeOpen: 0,//1：弹框打开；0：弹框关闭
      entryPlatDialogVisible: false,
      isReset: 0,//1：加入单位；0：重置
      joinComDialogVisible: false,
      compArr: [],
      ishow: false,
      current: 0, //当前操作按钮
      companyArr: []
    }
  },
  methods: {
    closeOne (val) {
      this.onlyOne = val
    },
    goBack () {//返回登录页面
      if (this.$route.query.topPage == '平台里跳转') {
        this.$router.push({ path: '/homepage' })
      } else {
        this.$router.push({ path: '/login' })
      }
    },
    getPlatList (row) {//平台授权的个数
      MyCompanyApi.getPlatList({
        params: {
          is_page: 0,
          company_id: row.company_id,
          status: 3//审核状态，2：审核中，3：通过，4：拒绝（驳回）
        }
      }).then((res) => {
        if (res.data.list.length > 0) {
          this.judgeOpen = 1;
          this.entryPlatObj = Object.assign({}, row);
          this.entryPlatDialogVisible = true;
        }
      }).catch((error) => {
        console.log('error')
      })
    },
    // onChangeComp () {//单位改变时触发的事件
    //   MyCompanyApi.getDefaultCompUpdateToken({
    //     data: {
    //       company_id: this.company_id//单位主键值
    //     }
    //   }).then((res) => {
    //     sessionStorage.setItem('access_token', res.data.access_token);//更新值
    //     this.handleCurrentChange(1);
    //   }).catch((error) => {
    //     console.log('error=', error)
    //   })
    // },
    handleCurrentChange (val) {//当前码改变时触发的事件
      this.requestParams.page = val;
      this.getMyCompany();
    },
    entryPlatHandleClose (done) {
      this.judgeOpen = 0;
      this.entryPlatObj = {};
      this.entryPlatDialogVisible = false;
      done()
    },
    //创建单位
    onAddOrLookCom (val, row) {
      if (this.$route.query.topPage == '平台里跳转') {
        this.$router.push({
          path: 'workbenchAddOrLookCom', query: { headTitle: val, org_id: val == "查看单位" ? row.company_id : '', topPage: '平台里跳转' }
        })
      } else {
        this.$router.push({
          path: 'workbenchAddOrLookCom', query: { headTitle: val, org_id: val == "查看单位" ? row.company_id : '' }
        })
      }
    },
    //子组件向父组件传值
    childValueToParent (val) {
      this.$store.state.hasTheUnitIncreaStatus = 0;
      this.isReset = 0;//重置
      this.joinComDialogVisible = false;
      this.getMyCompany();//刷新单位列表数据；
    },
    //加入单位
    onJoinCom () {
      this.isReset = 1;//加入单位
      this.joinComDialogVisible = true;
    },
    handleClose (done) {//弹框关闭前触发的事件
      this.$store.state.hasTheUnitIncreaStatus = 0;
      this.isReset = 0;//重置
      this.joinComDialogVisible = false;
      done();
    },
    //业务系统申请
    // onBusinessApp (row) {
    //   if (this.$route.query.topPage == '平台里跳转') {
    //     this.$router.push({ path: 'workbenchBusinessSystemApp', query: { company_id: row.company_id, company_name: row.company_name, topPage: '平台里跳转' } })
    //   } else {
    //     this.$router.push({ path: 'workbenchBusinessSystemApp', query: { company_id: row.company_id, company_name: row.company_name } })
    //   }
    // },
    //进入平台
    entryPlatf (row) {
      this.$router.push({ path: '/homepage', query: { current_company_id: row.company_id, current_org_id: row.org_id } });//v2.1.1版本更新
      // this.getPlatList(row);//v2.1.1版本更新
    },
    //显示操作项
    showDialog (index, item) {
      this.ishow = true;
      this.current = index;
    },
    //隐藏蒙层
    hideDialog (index, item) {
      this.ishow = false;
      this.current = null;
    },
    //获取默认单位列表
    getDefaultCom () {
      this.compArr = [];
      return MyCompanyApi.getMyCompany({
        params: {
          is_page: 0
        }
      }).then((res) => {
        if (res.data.list.length > 0) {
          this.compArr = res.data.list;
        }
      }).catch((error) => {
        console.log('error=', error)
      })
    },
    // 获取用户权限
    getUserAuth () {
      return userPermissionApi.getUserAuth({
        data: {
          user_id: JSON.parse(window.localStorage.userInfo).user_id
        }
      }).then(res => {
        let userAuthList = res.data.list;
        if (userAuthList) {
          this.$store.dispatch("setUserAuth", res.data.list);
        }
      },
        err => {
          console.log(err);
        }
      );
    },
    setUserMenu () {//设置用户菜单
      let roleInfo = {
        nav: {},
        topNav: []
      };
      this.$store.dispatch("addRole", roleInfo);
      let first = "";
      this.userMenu.map(item => {
        roleInfo.nav[item.menu_id] = item.children_list;
        roleInfo.topNav.push(item);
      });
      first = roleInfo.topNav[0].menu_id;
      window.localStorage.setItem("platFormRoleInfo", JSON.stringify(roleInfo));
      if (
        window.localStorage.getItem("platFormSideNav") === "undefined" ||
        window.localStorage.getItem("platFormSideNav") === null
      ) {
        this.$store.dispatch("sideNav", roleInfo.nav[first]);
        window.localStorage.setItem(
          "platFormSideNav",
          JSON.stringify(roleInfo.nav[first])
        );
      }
    },
    // 获取菜单
    getMenuTree () {
      this.$store.dispatch('sideNav', [])//左边菜单重置
      window.localStorage.setItem('platFormSideNav', JSON.stringify([]))//左边菜单重置
      let userId = window.localStorage.getItem("user_id");
      // console.log(this.$router.options.routes, 'add route')
      return userPermissionApi
        .getMenuTree({
          data: {
            user_id: userId
          }
        })
        .then(res => {
          // console.log(res, 'menu tree')
          let map = new Map();
          // 所有用户都要显示5个中心加首页，所以写死5个中心的菜单编号，与接口数据对比，没有就设置空数组
          let menuNoList = [
            { no: "project_center", name: "项目中心" },
            { no: "work-center", name: "工作中心" },
            { no: "personal-center", name: "个人中心" },
            { no: "resource-center", name: "资源中心" },
            { no: "config-center", name: "配置中心" },
            // { no: "work-bench", name: "工作台" }
          ];
          let menuList = [];
          if (res.data.list.length > 0) {
            // 以菜单编号为key，存入map
            res.data.list.map(item => {
              map.set(item.menu_no, item);
            });
            // 手动添加首页
            // menuList.push({
            //   menu_id: 'home_page',
            //   menu_name: '首页',
            //   route_url: 'homepage',
            //   menu_type: '1'
            // })
            // 遍历写死的菜单列表，与接口数据对比，有数据的以接口数据为准，没有的模拟一个对象
            menuNoList.map(menuNo => {
              let val = map.get(menuNo.no);
              if (val !== undefined) {
                menuList.push(val);
              } else {
                menuList.push({
                  menu_id: menuNo.no,
                  menu_name: menuNo.name,
                  children_list: []
                });
              }
            });
            // this.userMenu = res.data.list;
            this.userMenu = menuList;
            // this.$store.dispatch('setUserMenu', this.userMenu)
            this.setUserMenu();
          }
        });
    },

    onCompChange (val) {//单位改变后触发的事件（只有一个单位时）  
      //获取token
      MyCompanyApi.comChangeGetToken({//切换单位更新token值
        data: {
          company_id: val
        }
      }).then(async (res) => {
        if (res.code == 0) {
          // this.lookComp(val);//获取当前单位的信息
          this.$store.state.switchCompId = val;
          var userInfoObj = JSON.parse(window.localStorage.userInfo);
          userInfoObj.comp_id = val;
          JSON.parse(window.localStorage.userInfo)
          window.localStorage.setItem('userInfo', JSON.stringify(userInfoObj));//修改值
          // sessionStorage.setItem('access_token', res.data.access_token);//更新值
          localStorage.setItem('access_token', res.data.access_token);//更新值
          await this.getUserAuth();
          await this.getMenuTree();//获取菜单
          // location.reload();
        } else {
          this.company_id = this.$store.state.switchCompId == 0 ? '' : this.$store.state.switchCompId;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    //获取单位列表的数据
    getMyCompany () {
      return MyCompanyApi.getMyCompany({
        params: this.requestParams
      }).then((res) => {
        this.companyArr = res.data.list;
        if (this.companyArr.length > 0) {
          var count = 0;
          this.companyArr.forEach(ele => {
            if (ele.is_cur == 1) {
              this.company_id = ele.company_id;
              throw Error()
            } else {
              count = count + 1;
            }
          });
          if (count == this.companyArr.length) {//当前单位创建多个且没有is_cur=1时默认第一个单位为当前单位
            this.company_id = this.companyArr[0].company_id;
            this.onCompChange(this.companyArr[0].company_id)
          }
          this.guideDialog = false
        } else {
          if (this.onlyOne) {
            this.guideDialog = true
          }

        }
        this.total = res.data.total_count;
      }).catch((error) => {
        console.log('error=', error)
      })
    }
  },
  watch: {
    '$store.state.switchCompId': {//单位切换时监听s的事件
      handler (n, o) {
        this.company_id = n == 0 ? '' : n;
        // this.onChangeComp();
      },
      deep: true
    },
    // console.log('切换单位-switchCompId=', this.$store.state.switchCompId)
    joinDialog: { //加入组织弹窗关闭
      handler (n, o) {
        console.log(n);
        this.joinComDialogVisible = n
      },
      deep: true
    }
  },
  async created () {
    this.user_id = JSON.parse(window.localStorage.userInfo).user_id;
    // 获取二级域名
    this.hrefUrl = window.location.href;
    var s = this.hrefUrl;
    var h = s.split(".")[0];
    var a = h.split("//")[1];
    if (a === "www" || a === "WWW") {
      this.user_type = 3; // 管理
    } else {
      this.user_type = 4; // 普通
    }
    console.log('用户类型-user_type=', this.user_type)
    this.company_id = this.$store.state.switchCompId == 0 ? '' : this.$store.state.switchCompId;
    // this.company_id = JSON.parse(localStorage.companyInfo).company_name;//单位名称
    await this.getDefaultCom();//获取默认单位
    await this.getMyCompany();//获取单位列表的数据
  }
}
</script>

<style lang="scss" scoped>
.bottom-box {
  margin-bottom: 20px;
}
.handleDialog {
  position: absolute;
  text-align: center;
  width: 100%;
  height: 100%;
  bottom: 0;
  left: 0;
  z-index: 2;
  line-height: 155px;
}
.opera-button {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  height: 100%;
}
.unit-list {
  line-height: 40px;
}
#headerTitle .header-box {
  padding-bottom: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
  margin-top: 20px;
  border-bottom: 1px solid #d9d9d9;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-right: 20px;
}
.header-box span {
  font-size: 12px;
}
.select-style {
  margin-right: 12px;
}
.container {
  ul {
    overflow: hidden;
    width: calc(100%);
    padding-left: 0px;
  }
  ul li {
    box-shadow: 4px 4px 4px 4px #d0d0d0;
    width: -webkit-calc(33% - 20px);
    float: left;
    position: relative;
    height: 165px;
    margin-bottom: 20px;
  }
  ul > li {
    margin-left: 20px;
  }
  li {
    position: absolute;
    transition: 0.5s;
    -moz-transition: 0.5s; /* Firefox 4 */
    -webkit-transition: 0.5s; /* Safari and Chrome */
    -o-transition: 0.5s; /* Opera */
    border: 1px solid #666666;
    border-radius: 10px;
    z-index: 3;
    .li-content {
      padding: 20px;
      width: 100%;
      height: 165px;
      display: flex;
      flex-direction: row;
      .li-content-left {
        width: 35%;
        height: 100%;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .li-content-right {
        width: 65%;
        height: 100%;
        padding-left: 20px;
        .right-main-content {
          margin-top: 20px;
          height: 83px;
          overflow: auto;
        }
        .com-name {
          font-size: 14px;
          font-weight: bold;
        }
      }
    }
  }
  li:after {
    content: "";
    width: 100%;
    height: 0px;
    background-color: #333333;
    opacity: 0.3;
    position: absolute;
    bottom: 0;
    left: 0;
    transition: all 0.5s ease 0s;
    z-index: 1;
  }
  li:hover:after {
    height: 100%;
    border-radius: 10px;
  }
  li:hover {
    transform: translateY(0px) translateX(0px);
  }
}
.entry-plat /deep/ .el-dialog__body {
  //深度修改组件的某个样式
  padding-left: 0px !important;
}
/deep/ .el-icon-arrow-up:before {
  display: none;
}
</style>